<!--
 * @Description: 医嘱管理
 * @Author: 梁青春
 * @Date: 2025-10-11 14:59:52
 * @LastEditTime: 2025-11-18 16:23:52
 * @LastEditors: 梁青春
-->
<template>
  <navbar />
  <Container :showLeft="true" :showRight="false" leftWidth="320px">
    <template #left>
      <div class="left-heard search-input">
        <el-input
          v-model="queryParams.tenantCode"
          placeholder="搜索姓名/床位/出院号"
          clearable
          @change="handleSearch"
        />
      </div>
      <div class="left-body">
        <div class="select-all">
          <el-checkbox v-model="selectAll" @change="handleSelectAllPatient" label="全选" />
        </div>
        <div class="patient-list">
          <div class="patient-item" v-for="item in patientList" :key="item.id">
            <div class="patient-info">
              <div class="patient-checkbox">
                <el-checkbox v-model="item.selected" @change="handleSelectPatientChange" />
              </div>
              <div class="patient-name">{{ item.name }}</div>
              <div class="patient-gender">{{ item.gender }}</div>
              <div class="patient-age">{{ item.age }}</div>
              <div class="patient-bed">{{ item.bedNo }}</div>
              <div class="patient-tags">
                <StatusTag :statusTags="item.statusTags" rootClass="orders__tags" @tag-click="onPatientTagClick" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <div class="container-body" id="containerBody">
      <div class="main-herard tabs">
        <Tabs v-model="activeTab" :tabs="tabs" @change="onTabChange" />
      </div>
      <div class="main_body" :key="activeTab">
        <div class="search-box">
          <div class="search-box-left">
            <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="0">
              <el-form-item v-if="activeTab === 'verify' || activeTab === 'all'">
                <el-date-picker
                  v-model="queryParams.startTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始时间"
                  @change="handleQuery"
                />
              </el-form-item>
              <el-form-item v-if="activeTab === 'canceled'">
                <el-date-picker
                  v-model="queryParams.endTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择停止\撤销时间"
                  @change="handleQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-select v-model="queryParams.orderType" placeholder="请选择医嘱类型" @change="handleQuery">
                  <el-option
                    v-for="dict in sys_doctor_order_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-select v-model="queryParams.treatmentType" placeholder="请选择诊疗类型" @change="handleQuery">
                  <el-option
                    v-for="dict in sys_treatment_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item v-if="activeTab === 'execute'">
                <el-input placeholder="医嘱内容" v-model="queryParams.orderContent" clearable @change="handleQuery" />
              </el-form-item>
              <el-form-item v-if="activeTab === 'execute'">
                <el-checkbox label="未执行" v-model="queryParams.unExecuted" @change="handleQuery" />
              </el-form-item>
              <el-form-item v-if="activeTab === 'all'">
                <el-checkbox label="显示已撤销医嘱" v-model="queryParams.showCanceled" @change="handleQuery" />
              </el-form-item>
              <el-form-item v-if="activeTab === 'execute'">
                <el-checkbox label="未打印" v-model="queryParams.printed" @change="handleQuery" />
              </el-form-item>
            </el-form>
          </div>
          <div class="search-box-right">
            <el-button class="add-btn op-btn" type="primary" @click="handleCheck" v-if="activeTab === 'verify'"
              >核对</el-button
            >
            <el-button class="add-btn op-btn" type="primary" @click="handleExecute" v-if="activeTab === 'execute'"
              >执行</el-button
            >
            <el-button class="export-btn op-btn" type="warning" @click="handleCancel" v-if="activeTab === 'execute'"
              >撤销</el-button
            >
            <el-button
              class="export-btn op-btn"
              type="warning"
              @click="handleCancelCheck"
              v-if="activeTab === 'canceled' || activeTab === 'all'"
              >撤销核对</el-button
            >
            <el-button
              class="edit-btn op-btn"
              type="success"
              @click="handleAccount"
              v-if="activeTab === 'verify' || activeTab === 'all'"
              >记账</el-button
            >
            <el-button
              class="info-btn op-btn"
              type="info"
              @click="handlePrint"
              v-if="activeTab === 'execute' || activeTab === 'all'"
              >打印</el-button
            >
          </div>
        </div>
        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="orderList"
            @selection-change="handleSelectionChange"
            @row-click="openDetail"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="床位" prop="bedNo" align="center" width="55" />
            <el-table-column label="患者" prop="patientName" align="center" width="80" />
            <el-table-column label="开始时间" prop="startTime" align="center" width="100">
              <template #default="scope">
                {{ scope.row.startTime ? parseTime(scope.row.startTime, '{m}-{d} {h}:{i}') : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="类型" prop="orderType" align="center" width="80" />
            <el-table-column label="医嘱类型" prop="orderTypeLabel" align="center" width="80" />
            <el-table-column label="类别" prop="treatmentType" align="center" width="80" />
            <el-table-column label="状态" prop="statusLabel" align="center" width="80" />
            <el-table-column label="备注" prop="remark" align="center" show-overflow-tooltip />
            <el-table-column label="下达医生" prop="doctorName" align="center" width="80" />
            <el-table-column label="停止医生" prop="stopDoctorName" align="center" width="80" />
            <el-table-column label="停止时间" prop="stopTime" align="center" width="100">
              <template #default="scope">
                {{ scope.row.stopTime ? parseTime(scope.row.stopTime, '{m}-{d} {h}:{i}') : '-' }}
              </template>
            </el-table-column>
          </el-table>

          <el-drawer
            v-model="drawerVisible"
            :append-to="containerBody"
            :with-header="false"
            :show-close="false"
            size="60%"
            class="orders-drawer"
          >
            <div class="orders-drawer__header">
              <div class="orders-drawer__close" @click="handleCloseDrawer">
                <el-icon><Right /></el-icon>
              </div>
              <div class="orders-drawer__title">
                【{{ selectedOrder.orderTypeLabel || '医嘱' }}】
                {{ selectedOrder.drugName || selectedOrder.remark || '—' }}
                <span class="orders-drawer__spec">{{ selectedOrder.drugSpec || '' }}</span>
              </div>
              <div class="orders-drawer__sig">Sig: {{ selectedOrder.sig || '2片  口服  tid  首日: 1' }}</div>
              <div class="orders-drawer__meta">
                开始：{{ selectedOrder.doctorName || '-' }}
                {{ selectedOrder.startTime ? parseTime(selectedOrder.startTime, '{m}-{d} {h}:{i}') : '-' }}
                &nbsp;&nbsp; 停止：{{ selectedOrder.stopDoctorName || '-' }}
                {{ selectedOrder.stopTime ? parseTime(selectedOrder.stopTime, '{m}-{d} {h}:{i}') : '-' }}
              </div>
            </div>

            <el-tabs v-model="drawerTab" class="orders-drawer__tabs">
              <el-tab-pane label="执行明细" name="exec">
                <el-table :data="executeDetails" size="small">
                  <el-table-column label="计划时间" prop="planTime" width="120" />
                  <el-table-column label="状态" prop="status" width="80" />
                  <el-table-column label="执行护士" prop="nurse" width="100" />
                  <el-table-column label="执行时间" prop="execTime" width="120" />
                  <el-table-column label="执行单" prop="execSheet" width="120" />
                  <el-table-column label="发药" prop="dispense" width="80" />
                  <el-table-column label="发药科室" prop="dept" width="120" />
                  <el-table-column label="发药时间" prop="dispenseTime" width="120" />
                </el-table>
              </el-tab-pane>
              <el-tab-pane label="医嘱流转" name="flow">
                <div class="orders-drawer__placeholder">预留</div>
              </el-tab-pane>
              <el-tab-pane label="费用统计" name="fee">
                <div class="orders-drawer__placeholder">预留</div>
              </el-tab-pane>
              <el-tab-pane label="计费明细" name="billing">
                <div class="orders-drawer__placeholder">预留</div>
              </el-tab-pane>
            </el-tabs>
          </el-drawer>
        </div>
        <div class="queryParams-container">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="queryParams.pageSize"
            :current-page="queryParams.pageNum"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </Container>
</template>

<script setup name="Order">
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { parseTime } from '@/utils/ruoyi.js'
import Tabs from '@/components/Tabs/index.vue'
import StatusTag from '@/components/StatusTag/index.vue'
import { getOrderList, checkOrders, executeOrders, cancelOrders } from '@/mock/order.mock.js'

// 获取全局字典：医嘱类型、诊疗类型
const proxy = getCurrentInstance().proxy
const { sys_doctor_order_type } = proxy.useDict('sys_doctor_order_type')
const { sys_treatment_type } = proxy.useDict('sys_treatment_type')

// tabs数据：四个业务选项与计数徽章
const activeTab = ref('verify')
const orderCount = reactive({ verify: 0, execute: 0, canceled: 0, all: 0 })
const tabs = computed(() => [
  { label: '核对', value: 'verify', badge: orderCount.verify },
  { label: '执行', value: 'execute', badge: orderCount.execute },
  { label: '停止/撤销', value: 'canceled', badge: orderCount.canceled },
  { label: '全部', value: 'all', badge: orderCount.all }
])

// 查询参数与表格数据
const loading = ref(false)
const orderList = ref([])
const total = ref(0)
const selectedIds = ref([])

// 抽屉查看详情
const drawerVisible = ref(false)
const drawerTab = ref('exec')
const selectedOrder = ref({})
const selectAll = ref(false)

const data = ref({
  queryParams: {
    tenantCode: '',
    tenantName: '',
    startTime: '',
    endTime: '',
    orderType: '',
    treatmentType: '',
    orderContent: '',
    unExecuted: false,
    showCanceled: false,
    printed: false,
    pageNum: 1,
    pageSize: 10
  }
})
const { queryParams } = toRefs(data.value)
// 左侧患者列表示例（真实项目应替换为后端接口）
const patientList = ref([
  { id: 'p1', name: '张三苏', gender: '男', age: 34, bedNo: '01A', statusTags: ['新', '在', 'Ⅰ', '执', '核'] },
  { id: 'p2', name: '李四奇', gender: '女', age: 29, bedNo: '01B', statusTags: ['在', '3', '执'] },
  { id: 'p3', name: '王五谷', gender: '男', age: 41, bedNo: '02A', statusTags: [] }
])

// 选中患者状态：全选/取消全选
const handleSelectAllPatient = val => {
  patientList.value.forEach(item => (item.selected = val))
}

// 选中患者状态：单个选择/取消
const handleSelectPatientChange = item => {
  item.selected = !item.selected
}

// 加载列表并统计数量
const fetchOrders = async () => {
  loading.value = true
  try {
    const { data } = await getOrderList({
      status: activeTab.value,
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      filters: {
        bedNo: '',
        patientName: '',
        orderType: queryParams.value.orderType,
        treatmentType: queryParams.value.treatmentType,
        startTime: queryParams.value.startTime,
        endTime: queryParams.value.endTime,
        orderContent: queryParams.value.orderContent
      }
    })
    orderList.value = data.list
    total.value = data.total

    // 统计计数徽章：基于全量数据
    const { data: allData } = await getOrderList({ status: 'all', pageNum: 1, pageSize: 9999 })
    orderCount.all = allData.total
    orderCount.verify = allData.list.filter(i => i.status === 'verify').length
    orderCount.execute = allData.list.filter(i => i.status === 'execute').length
    orderCount.canceled = allData.list.filter(i => i.status === 'canceled').length
  } finally {
    loading.value = false
  }
}

// 业务：切换tab并应用过滤逻辑
const onTabChange = async value => {
  activeTab.value = value
  await fetchOrders()
}

// 查询相关交互
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchOrders()
}
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchOrders()
}
const handlePageChange = page => {
  queryParams.pageNum = page
  fetchOrders()
}

// 表格选择
const handleSelectionChange = rows => {
  selectedIds.value = rows.map(r => r.id)
}

// 点击行打开抽屉展示详情
const openDetail = row => {
  selectedOrder.value = { ...row }
  drawerTab.value = 'exec'
  drawerVisible.value = true
}
const handleCloseDrawer = () => {
  drawerVisible.value = false
}
// 执行明细示例数据（真实项目替换为后端返回）
const executeDetails = computed(() => {
  const baseTime = selectedOrder.value.startTime || '2025-04-25 15:02:00'
  return [
    {
      planTime: '04-26 15:02',
      status: '完成',
      nurse: '周连茹',
      execTime: '04-26 15:04',
      execSheet: '20240524001',
      dispense: '已发',
      dept: '呼吸内科',
      dispenseTime: '04-26 15:04'
    },
    {
      planTime: '04-25 15:02',
      status: '完成',
      nurse: '周连茹',
      execTime: '04-25 15:04',
      execSheet: '20240524001',
      dispense: '已发',
      dept: '呼吸内科',
      dispenseTime: '04-25 15:04'
    },
    {
      planTime: '04-25 15:02',
      status: '计划',
      nurse: '周连茹',
      execTime: '04-25 15:04',
      execSheet: '20240524001',
      dispense: '已发',
      dept: '呼吸内科',
      dispenseTime: '04-25 15:04'
    }
  ]
})

// 业务操作：核对、执行、撤销、撤销核对、记账、打印
const handleCheck = async () => {
  if (!selectedIds.value.length) return proxy.$modal.notifySuccess('请先选择医嘱')
  await checkOrders(selectedIds.value)
  proxy.$modal.notifySuccess('核对成功')
  fetchOrders()
}
const handleExecute = async () => {
  if (!selectedIds.value.length) return proxy.$modal.notifySuccess('请先选择医嘱')
  await executeOrders(selectedIds.value)
  proxy.$modal.notifySuccess('执行成功')
  fetchOrders()
}
const handleCancel = async () => {
  if (!selectedIds.value.length) return proxy.$modal.notifySuccess('请先选择医嘱')
  await cancelOrders(selectedIds.value)
  proxy.$modal.notifySuccess('撤销成功')
  fetchOrders()
}
const handleCancelCheck = async () => {
  if (!selectedIds.value.length) return proxy.$modal.notifySuccess('请先选择医嘱')
  await checkOrders(selectedIds.value)
  proxy.$modal.notifySuccess('已撤销核对')
  fetchOrders()
}
const handleAccount = () => {
  proxy.$modal.notifySuccess('记账成功（演示）')
}
const handlePrint = () => {
  proxy.$modal.notifySuccess('已发送打印任务（演示）')
}

// 左侧标签点击（演示）
const onPatientTagClick = tag => {
  proxy.$modal.notifySuccess(`点击患者状态标签：${tag}`)
}

onMounted(() => {
  fetchOrders()
})
</script>

<style lang="scss" scoped>
@use '@/assets/styles/variables.module.scss' as *;

.left-heard {
  display: flex;
  gap: $margin-md;
  padding: $padding-md;
  background: #fff;
  border-bottom: 1px solid $border-color;
  &.search-input {
    padding: $padding-sm $padding-md;
  }
}

.left-body {
  background: #fff;
  height: calc(100% - $sub-navbar-height);
}
.select-all {
  display: flex;
  align-items: center;
  background: #fff;
  gap: $margin-md;
  padding: $padding-md;
  border-bottom: 1px solid $border-color;
}
.patient-list {
  display: flex;
  flex-direction: column;
}

.patient-item {
  border-bottom: 1px solid $border-color;
  background: #fff;
  padding: $padding-md;
}

.patient-info {
  display: grid;
  grid-template-columns: 24px 50px 24px 24px 1fr;
  align-items: center;
}

.patient-tags {
  grid-column: 1 / -1;
  margin-top: $margin-sm;
}

.main_herard {
  background: #fff;
}
.tabs {
  display: flex;
  align-items: center;
}

.search-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: $margin-md;
  padding: $padding-md;
  border-bottom: 1px solid $border-color;
  :deep(.el-form-item--default) {
    margin-bottom: 0;
  }
}

.op-btn {
  margin-left: $margin-sm;
}

.table-container {
  padding: $padding-md;
}

.queryParams-container {
  display: flex;
  justify-content: center;
  padding-bottom: $padding-md;
}

/* 抽屉样式 */
.orders-drawer {
  position: relative;
  :deep(.el-drawer__body) {
    padding: $padding-md;
    background: #fff;
  }
}
.orders-drawer__header {
  padding-bottom: $padding-md;
  border-bottom: 1px solid $border-color;
}
.orders-drawer__close {
  position: absolute;
  top: $padding-md;
  right: $padding-md;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: $font-size-lg;
  width: 24px;
  height: 24px;
  color: #606266;
  cursor: pointer;
}
.orders-drawer__title {
  font-weight: 700;
  font-size: 16px;
}
.orders-drawer__spec {
  margin-left: 8px;
  color: #606266;
}
.orders-drawer__sig {
  margin-top: 6px;
  color: #606266;
}
.orders-drawer__meta {
  margin-top: 6px;
  color: #606266;
}
.orders-drawer__tabs {
  margin-top: $margin-md;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .patient-info {
    grid-template-columns: 24px 1fr auto;
  }
  .search-box {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
<style lang="scss">
.container-body {
  position: relative;
  .el-overlay {
    position: absolute !important;
  }
}
</style>
